<script setup>
import { ref, inject } from 'vue';
import { ElMessage } from "element-plus";
import { Check } from '@element-plus/icons-vue'

const http = inject('$http'),
	router = inject('$router'),
	store = inject('$store');

const query = router.currentRoute.value.query;

const afterLoginUrl = query['back'] ? query['back'] : '/';

/** 数据 */

let loading = ref(false);

const refLoginForm = ref(null)
let formData = ref({ username: '', password: '' })
const rules = ref({
	username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
})

/** 方法 */
const login = () => {
	console.log(store.state);
	if (!refLoginForm.value) return
	refLoginForm.value.validate(async (valid) => {
		if (!valid) return false
		loading.value = true
		const login = await http.post('/login', formData.value);
		loading.value = false
		if (login && login.code === 200) {
			store.dispatch('logined', login.data);
			ElMessage({ type: 'success', message: login.message })
			router.replace(afterLoginUrl)
			return;
		}
		let errMsg = '登录失败，请稍后再试';
		if (login && login['message']) errMsg = login.message;
		ElMessage({ type: 'error', message: errMsg })
	})
}

</script>

<template>
	<el-form :disabled="loading" :rules="rules" ref="refLoginForm" :model="formData" @submit.native.prevent="login"
		class="loginContainer">
		<h3 style="text-align: center;">管理员登录</h3>
		<el-form-item prop="username">
			<el-input type="text" auto-complete="false" v-model="formData.username" placeholder="请输入用户名"></el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input type="password" auto-complete="false" v-model="formData.password" placeholder="请输入登录密码"></el-input>
		</el-form-item>
		<el-button type="primary" style="width:100%" :icon="Check" :loading="loading" native-type="submit">立即登录</el-button>
	</el-form>
</template>

<style lang="scss" scoped>
.loginContainer {
	border-radius: 10px;
	width: 350px;
	padding: 5px 20px 20px;
	box-shadow: 0 0 10px #bbb;
	background: #fff;
	position: absolute;
	left: 50%;
	top: 35%;
	transform: translate(-50%, -50%);

	h3 {
		margin: 20px auto;
	}

}
</style>